//
//  MePhotosViewController.m
//  BGM
//
//  Created by liuqin on 2018/12/4.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "MePhotosViewController.h"
#import "BGMUser.h"
#import "Common.h"
#import <MobileCoreServices/MobileCoreServices.h>
//#import "ZYQAssetPickerController.h"
#import "AFHTTPSessionManager.h"
//ASSet需要导入
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import "QBImagePickerController.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "BGMHTTP.h"
#import "SVProgressHUD.h"

#import "BGMNewImage.h"
#import "PushImageClass.h"
#import "GCQiniuUploadManager.h"
#import "QiniuSDK.h"


@interface MePhotosViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate, UIImagePickerControllerDelegate,QBImagePickerControllerDelegate>

@property (nonatomic, strong)NSMutableArray *dataArray;   //用户图片url
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic,strong)QBImagePickerController *picker;
@property (nonatomic,strong)NSMutableString *imageStr;

@property (nonatomic,strong)NSMutableArray *oldImageUrl;

@property (nonatomic,assign)BOOL isEdit;


@end

@implementation MePhotosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    CGRect rect = self.titleBtn.frame;
    rect.size.width = rect.size.width+70;
    self.titleBtn.frame = rect;
    [self.titleBtn setTitle:@"照片墙" forState:UIControlStateNormal];
    self.dataArray = [[NSMutableArray alloc]init];
    self.oldImageUrl = [[NSMutableArray alloc]init];
    self.imageStr = [[NSMutableString alloc]initWithString:@""];
    if(self.isOther){
        
        self.navRightBtn.hidden = YES;
        
    }else{
        
        self.navRightBtn.hidden = NO;
        [self.navRightBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [self.navRightBtn setTitleColor:bgmmainColor forState:UIControlStateNormal];
        [self.navRightBtn setTitle:@"完成" forState:UIControlStateSelected];

        
        id array = [BGMUser shareInstance].imageArray;
        if ([array isKindOfClass:[NSArray class]]) {
            self.imageArray = [[NSMutableArray alloc]init];
            [self.imageArray addObjectsFromArray:[BGMUser shareInstance].imageArray];
        }else{
            NSLog(@"asdfsaf");
        }
    }
    
 
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(15,self.navview.frame.size.height+15, SCREENW-30, ((SCREENW-50)/3) *3+50) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"PhtotoCollectionViewCell"];
    
    
    if(!self.isOther){
        UIButton *bottomBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, self.collectionView.frame.origin.y+self.collectionView.frame.size.height+30, SCREENW-30, 45)];
        bottomBtn.backgroundColor = bgmyelloeColor;
        bottomBtn.layer.masksToBounds = YES;
        bottomBtn.layer.cornerRadius = 8;
        [bottomBtn setTitle:@"保存" forState:UIControlStateNormal];
        [self.view addSubview:bottomBtn];
        [bottomBtn addTarget:self action:@selector(clickBottom) forControlEvents:UIControlEventTouchUpInside];
    }
 
}


#pragma mark --UICollectionViewDataSource,UICollectionViewDelegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.isOther) {
       return self.imageArray.count;
    }else{
      return self.imageArray.count == 9 ? 9 : self.imageArray.count+1;
    }
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifer = @"PhtotoCollectionViewCell" ;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];
    cell.backgroundColor= [UIColor clearColor];
    UIImageView *photoImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, (SCREENW-30-20)/3, (SCREENW-30-20)/3)];
    photoImage.backgroundColor = bgmColor(224, 224, 224);
    photoImage.tag = indexPath.row;
    photoImage.contentMode = UIViewContentModeScaleAspectFit;
    photoImage.userInteractionEnabled = NO;
    [cell addSubview:photoImage];
    
    
    UIButton *btn =[[ UIButton alloc]initWithFrame:CGRectMake((SCREENW-30-20)/3-30, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"deleImage"] forState:UIControlStateNormal];
    btn.tag = indexPath.row;
    [cell addSubview:btn];
    [btn addTarget:self action:@selector(clickDele:) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.isOther) {
        NSString *url = [self.imageArray objectAtIndex:indexPath.row];
        [photoImage sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"imageNormal"]];
        btn.hidden = YES;
    }else{
        if (self.isEdit) {
            btn.hidden = NO;
        }else{
            btn.hidden = YES;
        }
        
        
        if (self.imageArray.count<9) {
            if (indexPath.row==self.imageArray.count) {
                [photoImage setImage:[UIImage imageNamed:@"push_addImage"]];
                btn.hidden = YES;
            }else{
                id imageObject = [self.imageArray objectAtIndex:indexPath.row];
                if ([imageObject isKindOfClass:[NSString class]]) {
                    NSString *url = [self.imageArray objectAtIndex:indexPath.row];
                    [photoImage sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"imageNormal"]];
                }else{
                    [photoImage setImage:[self.imageArray objectAtIndex:indexPath.row]];

                }
             
            }
        }else{
            
            id imageObject = [self.imageArray objectAtIndex:indexPath.row];
            if ([imageObject isKindOfClass:[NSString class]]) {
                NSString *url = [self.imageArray objectAtIndex:indexPath.row];
                [photoImage sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"imageNormal"]];
            }else{
                [photoImage setImage:[self.imageArray objectAtIndex:indexPath.row]];
                
            }
            
        }
    }
    return cell;
}
- (void)clickDele:(UIButton *)btn{
    
    int tag = (int)btn.tag;
    [self.imageArray removeObjectAtIndex:tag];
    [self.collectionView reloadData];
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREENW-30-20)/3, (SCREENW-30-20)/3+15);
}
//
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0,0,0, 0);
    
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(self.isOther){
        return ;
    }else{
        
        if(indexPath.row != self.imageArray.count){
            return;
        }
        
    }
    
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消 " style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                         }];
    UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             //                                                                     NSLog(@"action = %@", action);
                                                             [self seleHeadImage:1];
                                                         }];
    UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                                                           //响应事件
                                                           //                                                                   NSLog(@"action = %@", action);
                                                           [self seleHeadImage:2];
                                                       }];
    [alert addAction:saveAction];
    [alert addAction:cancelAction];
    [alert addAction:deleteAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isOther) {
        return NO;
    }else{
         return YES;
    }
}
//1拍 2 选
- (void)seleHeadImage:(int)i {
    
    // 判断系统是否支持相机
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    if (i == 1) {
        //拍照
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else {
         //相册
        self.picker.maximumNumberOfSelection = 9-self.imageArray.count;
        [self presentViewController:self.picker animated:YES completion:nil];
    }
    
    
}
// 获取图片后操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *) kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImage *edit = [info objectForKey:UIImagePickerControllerEditedImage];
        [self.imageArray addObject:edit];
        [self.collectionView reloadData];
 
        
    }
    // 销毁控制器
    [self upImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)upImage{
//    NSDictionary *param = @{@"file":@"file"};
//
//    [[AFHTTPSessionManager manager]POST:[NSString stringWithFormat:@"%@%@",Server_url,@"upload/txUploadImg"] parameters:param headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        [formData appendPartWithFileData:UIImageJPEGRepresentation(self.userImage, 1.0) name:@"file" fileName:@"iOS.png" mimeType:@"image/png"];
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"asdfaf");
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [self getUserImageURL:responseObject];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"asdfsaf");
//    }];
//
}
- (void)getUserImageURL:(NSDictionary *)dic{
    dispatch_async(dispatch_get_main_queue(), ^{
//        self.userImageURL = [NSString stringWithFormat:@"%@",[dic objectForKey:@"data"]];
//        [self change];
    });
}

- (QBImagePickerController*)picker{
    if (!_picker) {
        _picker = [[QBImagePickerController alloc]init];
        _picker.delegate = self;
        _picker.automaticallyAdjustsScrollViewInsets = YES;
        _picker.minimumNumberOfSelection = 0;
        //指定显示的相册
        _picker.assetCollectionSubtypes = @[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary)];
        //设置媒体类型
        _picker.mediaType = QBImagePickerMediaTypeAny;//图片与视频
        //设置每行显示的图像数量
        _picker.numberOfColumnsInPortrait = 4;//竖屏下每行4个
        _picker.numberOfColumnsInLandscape = 7;//横惬意下每行7个
        _picker.prompt = @"请选择图片";
        _picker.showsNumberOfSelectedAssets = YES;
        _picker.allowsMultipleSelection = YES;
    }
    [_picker.selectedAssets removeAllObjects];
    //    [_picker.selectedAssets addObjectsFromArray:self.showEditItem.selectedAssets];
    return _picker;
}


- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    
    if (assets.count == 0) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return ;
    }else{
        
        [self getLibraryPhotoImage:assets];
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getLibraryPhotoImage:(NSArray *)assets{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        for (PHAsset *asset in assets) {
            PHImageManager * imageManager = [PHImageManager defaultManager];
            [imageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                UIImage * image = [UIImage imageWithData:imageData];
                [self.imageArray addObject:image];
                [self.collectionView reloadData];
            }];
            
        }
    });
}


//点击取消按扭
- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 上传
- (void)clickRight{
    self.isEdit = !self.isEdit;
    [self.collectionView reloadData];
    self.navRightBtn.selected = !self.navRightBtn.selected;

}
- (void)clickBottom{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD showWithStatus:@"修改中"];
    
    if (self.imageArray.count == 0) {
        [self pushPhoto];
    }else{
        if (self.imageArray.count==1) {
            [self upOneImage];
        }else{
            [self upSomeImage];
        }
    }

}

- (void)upOneImage{
    
    
    for (int i = 0;i<self.imageArray.count;i++) {
        id imageObject = [self.imageArray objectAtIndex:i];
        
        if ([imageObject isKindOfClass:[NSString class]]) {
            [self.imageStr appendString:imageObject];
            [self pushPhoto];
        }else{
            BGMNewImage *newImage = [[BGMNewImage alloc]init];
            UIImage *image = [self.imageArray objectAtIndex:0];
            NSData *data = [newImage resetSizeOfImageData:image maxSize:1024];
            
            
            NSString *token =  [[GCQiniuUploadManager sharedInstance] createToken];
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            QNUploadOption *up = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
                
            } params:nil checkCrc:NO cancellationSignal:nil];
            
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval a=[dat timeIntervalSince1970];
            NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
            NSString *name = [NSString stringWithFormat:@"%@_iosPush.png",timeString];
            
            [upManager putData:data key:name token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                NSString *url = [NSString stringWithFormat:@"http://yaobangma.com/%@",[resp objectForKey:@"key"]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.imageStr appendString:url];
                    
                    [self pushPhoto];
                });
            } option:up];
            
        }
    }
    
    
   
 
    
}

- (void)upSomeImage{
    
  
    
    NSMutableArray *imageData = [[NSMutableArray alloc]init];
    for (int i = 0;i<self.imageArray.count;i++) {
        id imageObject = [self.imageArray objectAtIndex:i];
        if ([imageObject isKindOfClass:[NSString class]]) {
            [self.oldImageUrl addObject:imageObject];
        }else{
            BGMNewImage *newImage = [[BGMNewImage alloc]init];
            UIImage *image = [self.imageArray objectAtIndex:i];
            NSData *data = [newImage resetSizeOfImageData:image maxSize:1024];
            PushImageClass *imageclass = [[PushImageClass alloc]init];
            imageclass.imageData = data;
            imageclass.isCompele = NO;
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval a=[dat timeIntervalSince1970];
            NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
            NSString *name = [NSString stringWithFormat:@"%d_%@_iosPush.png",i,timeString];
            imageclass.fileName = name;
            [imageData addObject:imageclass];
        }
    }
    
    if(imageData.count==0){
        for (NSString *url in self.oldImageUrl) {
            [self.imageStr appendFormat:@"%@,",url];
        }
        [self pushPhoto];
    }else{
        NSString *token =  [[GCQiniuUploadManager sharedInstance] createToken];
        [self uploadFileWithImages:imageData index:0 token:token completed:^(NSArray<PushImageClass *> *list){
            dispatch_async(dispatch_get_main_queue(), ^{
                for (PushImageClass *imageClass in list) {
                    [self.imageStr appendFormat:@"%@,",imageClass.fileUrl];
                }
                for (NSString *url in self.oldImageUrl) {
                    [self.imageStr appendFormat:@"%@,",url];
                }
                [self pushPhoto];
            });
        }];
    }
 
}

- (void)uploadFileWithImages:(NSArray<PushImageClass *> *)entitys index:(NSInteger)index token:(NSString *)token
                   completed:(void (^)(NSArray<PushImageClass *> *list))completion{
    
    if(index>=0&&index<[entitys count]){
        PushImageClass *entity = entitys[index];
        [self uploadFileWithToken:token push:entity completed:^(NSString *url,BOOL boo){
            
            if(boo){
                entity.fileUrl = url;
            }
            entity.isCompele=boo;
            
            if(index+1 >[entitys count]-1){
                if (completion) {
                    completion(entitys);
                }
            }else{
                [self uploadFileWithImages:entitys index:index+1 token:token completed:completion];
            }
            
        }];
    }
    
}

- (void)uploadFileWithToken:(NSString *)token push:(PushImageClass *)entity
                  completed:(void (^)(NSString *url,BOOL boo))success
{
    NSData *data = entity.imageData;
    if (!data) {
        if (success) {
            success(nil,NO);
        }
        return;
    }
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *up = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
    } params:nil checkCrc:NO cancellationSignal:nil];
    [upManager putData:data key:entity.fileName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSString *url = [NSString stringWithFormat:@"http://yaobangma.com/%@",[resp objectForKey:@"key"]];
        if (success) {
            success(url,YES);
        }
    } option:up];
}





- (void)getImageURL:(id)url{
    if ([url isKindOfClass:[NSString class]]) {
        [self.imageStr appendString:url];
    }else{
        NSArray *array = url;
        for (NSString *url in array) {
            [self.imageStr appendFormat:@"%@", [NSString stringWithFormat:@"%@,",url]];
        }
    }
    
    [self pushPhoto];
}
-(void)pushPhoto{
 
    NSDictionary *dic = @{@"userToken":[BGMUser shareInstance].userToken,
                          @"userId":[BGMUser shareInstance].userId,
                          @"image":self.imageStr,
                          @"name":[BGMUser shareInstance].name,
                          @"gender":[BGMUser shareInstance].gender,
                          @"birthday":[BGMUser shareInstance].birthday,
                          @"city":[BGMUser shareInstance].city,
                          @"industry":[BGMUser shareInstance].industry,
                          @"personalLabel":@"",
                          @"headImage":[BGMUser shareInstance].headImage
                          };
    [BGMHTTP requestWithMethodName:@"users/editUserInfo" parameters:dic completion:^(BOOL success, NSError *error, NSDictionary *result) {
        if(success){
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            NSDictionary *dic = [result objectForKey:@"data"];
            [self saveInfomation:dic];
        }else{
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
        }
    }];
}
- (void)saveInfomation:(NSDictionary *)dictory{
    BGMUser *user = [BGMUser shareInstance];
    user.imageArray = [dictory objectForKey:@"image"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"chageimageArray" object:nil];
    [self.navigationController popViewControllerAnimated:YES];

}
@end
